import math

class ADWIN(object):
    """description of class"""
    def __init__(self, thres, delta, minTick, minWinLen):
        self.thres = thres
        self.delta = delta
        self.__window=[]
        self.__time = 0
        self.minTick = minTick
        self.minWinLen = minWinLen

    def add(self, v):
        self.__window.append(v)
        self.__time=self.__time+1
        if(self.__time % self.minTick==0 and len(self.__window)>self.minWinLen):
            tobigger = 0
            tosmaller = 0
            while True:
                flag = self.__detectedChange()
                if flag>0:
                    tosmaller = tosmaller+1
                elif flag<0:
                    tobigger = tobigger+1
                else:
                    break
                self.__window.pop(0)
            if tobigger>=tosmaller and tobigger>0:
                return self.__window
            else:
                return None
        else:
            return None

    def __detectedChange(self):
        n = len(self.__window)
        for n0 in range(1,n):
            u0 = sum( [item[0] for item in self.__window[:n0]]  )*1.0/ n0
            u1 = sum( [item[0] for item in self.__window[n0:]]  )*1.0/ (n-n0)
            #e = self.__calcEpsilon(n0,n-n0)
            e=self.thres
            if u0-u1>e:
                return 1
            elif u1-u0>e:
                return -1
        return 0

    def __calcEpsilon(self,n0,n1):
        m = 1.0/(1.0/n0+1.0/n1)
        dlt = self.delta/(n0+n1)
        return math.sqrt(1.0/(2*m)*math.log(4/dlt))